package xcmg.device.service.agent;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.agent.ServiceBasicDataAgentDO;
import xcmg.device.dao.mapper.agent.ServiceBasicDataAgentMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.vo.agent.ServiceBasicDataAgentVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ServiceBasicDataAgent 后台接口实现类
 *
 * @author huhuawei
 */
@Service
public class ServiceBasicDataAgentService {


    private static final Logger logger = LoggerFactory.getLogger(ServiceBasicDataAgentService.class);


    @Autowired
    private ServiceBasicDataAgentMapper serviceBasicDataAgentMapper;

    @Autowired
    private FastGenClient fastGenClient;

    /**
     * 查询列表
     *
     * @param condition
     */
    public PageCommonVO<ServiceBasicDataAgentVO> list(SearchCommonVO<ServiceBasicDataAgentVO> condition, String orgId) {
        if (null == condition.getFilters()) {
            condition.setFilters(new ServiceBasicDataAgentVO());
        }
        PageCommonVO<ServiceBasicDataAgentVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        ServiceBasicDataAgentVO serviceBasicDataAgentVO = condition.getFilters();
        if (StringUtils.isEmpty(serviceBasicDataAgentVO.getOrgId())) {
            serviceBasicDataAgentVO.setOrgId(orgId);
        }
        List<ServiceBasicDataAgentDO> queryList = serviceBasicDataAgentMapper.queryList(serviceBasicDataAgentVO);
        List<ServiceBasicDataAgentVO> voList = new ArrayList<ServiceBasicDataAgentVO>();
        for (ServiceBasicDataAgentDO entity : queryList) {
            ServiceBasicDataAgentVO serviceStaffQuotaVO = new ServiceBasicDataAgentVO();
            BeanUtils.copyProperties(entity, serviceStaffQuotaVO);
            voList.add(serviceStaffQuotaVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(queryList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 查询列表
     *
     * @param vo
     */
    public List<ServiceBasicDataAgentVO> queryList(ServiceBasicDataAgentVO vo) {
        List<ServiceBasicDataAgentDO> queryList = serviceBasicDataAgentMapper.queryList(vo);
        List<ServiceBasicDataAgentVO> voList = new ArrayList<ServiceBasicDataAgentVO>();
        for (ServiceBasicDataAgentDO entity : queryList) {
            ServiceBasicDataAgentVO serviceStaffQuotaVO = new ServiceBasicDataAgentVO();
            BeanUtils.copyProperties(entity, serviceStaffQuotaVO);
            voList.add(serviceStaffQuotaVO);
        }
        return voList;
    }


    /**
     * 查询单条记录
     *
     * @param id
     */
    public ServiceBasicDataAgentVO queryById(String id) {
        ServiceBasicDataAgentVO vo = new ServiceBasicDataAgentVO();
        vo.setId(id);
        List<ServiceBasicDataAgentVO> list = queryList(vo);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 保存数据
     *
     * @param serviceBasicDataAgentVO
     * @param userId
     * @param userName
     * @param orgId
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode save(ServiceBasicDataAgentVO serviceBasicDataAgentVO, String userId, String userName, String orgId) throws Exception {
        //初始时候数据状态
        return doSave(serviceBasicDataAgentVO, userId, userName, orgId);
    }

    /**
     * 根据状态，等信息保存数据
     *
     * @param serviceBasicDataAgentVO
     * @param userId
     * @param userName
     * @param orgId
     */
    private ErrorCode doSave(ServiceBasicDataAgentVO serviceBasicDataAgentVO, String userId, String userName, String orgId) throws Exception {
        serviceBasicDataAgentVO.setOrgId(orgId);
        if (StringUtils.isEmpty(serviceBasicDataAgentVO.getpCode())) {
            //默认父节点为0
            serviceBasicDataAgentVO.setpCode("0");
        }
        preSaveCheck(serviceBasicDataAgentVO);
        ServiceBasicDataAgentDO serviceBasicDataAgentDO = new ServiceBasicDataAgentDO();
        BeanUtils.copyProperties(serviceBasicDataAgentVO, serviceBasicDataAgentDO);
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            return ErrorCode.IllegalArument;
        }
        if (StringUtils.isBlank(serviceBasicDataAgentDO.getId())) {
            serviceBasicDataAgentDO.setCreateId(userId);
            serviceBasicDataAgentDO.setCreateName(userName);
            serviceBasicDataAgentDO.setOrgId(orgId);
            serviceBasicDataAgentDO.setCreateDate(new Date());
            serviceBasicDataAgentDO.setId(textResult.getValue());
            logger.info("新增操作，serviceBasicDataAgentDO:{}", serviceBasicDataAgentDO);
        } else {
            serviceBasicDataAgentDO.setUpdateDate(new Date());
            serviceBasicDataAgentDO.setUpdateId(userId);
            //更新子集
            boolean result = updateSubset(orgId, serviceBasicDataAgentDO);
            if (result) {
                return ErrorCode.Failure;
            }
            logger.info("编辑操作，serviceBasicDataAgentDO:{}", serviceBasicDataAgentDO);
        }
        boolean isSuccess = this.merge(serviceBasicDataAgentDO) > 0;
        if (!isSuccess) {
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }

    //更新子集
    private boolean updateSubset(String orgId, ServiceBasicDataAgentDO serviceBasicDataAgentDO) {
        String pCode = serviceBasicDataAgentDO.getPCode();
        if (!"0".equals(pCode)) {
            return false;
        }
        ServiceBasicDataAgentDO basicDataAgentDO = serviceBasicDataAgentMapper.selectByPrimaryKey(serviceBasicDataAgentDO.getId());
        if (null == basicDataAgentDO) {
            return false;
        }
        String oldPCode = basicDataAgentDO.getCode();
        String newPCode = serviceBasicDataAgentDO.getCode();
        serviceBasicDataAgentMapper.updateByPCode(oldPCode, newPCode, orgId);
        return false;
    }

    /**
     * 保存前信息校验
     */
    private void preSaveCheck(ServiceBasicDataAgentVO serviceBasicDataAgentVO) throws Exception {
        if (null == serviceBasicDataAgentVO) {
            throw new Exception(ErrorCode.IllegalArument.getDesc());
        }
        //TODO如果是提交操作或者某些状态下需要做校验吗？
        //        if (isSubmit&&status？？？) {
        //        }
        if (StringUtils.isNotBlank(serviceBasicDataAgentVO.getId())) {
            //编辑的时候 检验 org_id 和 code的唯一性
            ServiceBasicDataAgentVO serviceBasicDataAgentVO1 = new ServiceBasicDataAgentVO();
            serviceBasicDataAgentVO1.setUpdateValidateId(serviceBasicDataAgentVO.getId());
            serviceBasicDataAgentVO1.setCode(serviceBasicDataAgentVO.getCode());
            serviceBasicDataAgentVO1.setOrgId(serviceBasicDataAgentVO.getOrgId());
            serviceBasicDataAgentVO1.setpCode(serviceBasicDataAgentVO.getpCode());
            List<ServiceBasicDataAgentDO> serviceBasicDataAgentDOS = serviceBasicDataAgentMapper.queryList(serviceBasicDataAgentVO1);
            if (serviceBasicDataAgentDOS.size() > 0) {
                throw new Exception(ErrorCode.ServiceBasicDataAgentInfoIsExisted.getDesc());
            }
        } else {
            //新增的时候做唯一性的校验
            //编辑的时候 检验 org_id 和 code的唯一性
            ServiceBasicDataAgentVO serviceBasicDataAgentVO2 = new ServiceBasicDataAgentVO();
            serviceBasicDataAgentVO2.setCode(serviceBasicDataAgentVO.getCode());
            serviceBasicDataAgentVO2.setOrgId(serviceBasicDataAgentVO.getOrgId());
            serviceBasicDataAgentVO2.setpCode(serviceBasicDataAgentVO.getpCode());
            List<ServiceBasicDataAgentDO> serviceBasicDataAgentDOS = serviceBasicDataAgentMapper.queryList(serviceBasicDataAgentVO2);
            if (serviceBasicDataAgentDOS.size() > 0) {
                throw new Exception(ErrorCode.ServiceBasicDataAgentInfoIsExisted.getDesc());
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public int merge(ServiceBasicDataAgentDO dto) {
        return serviceBasicDataAgentMapper.merge(dto);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode batchDelete(List<String> ids) throws Exception {
        if (CollectionUtils.isEmpty(ids)) {
            return ErrorCode.Failure;
        }
        for (String id : ids) {
            int i = serviceBasicDataAgentMapper.deleteByPrimaryKeySelective(id);
            if (i == 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }
        return ErrorCode.Success;
    }

    public Integer checkDoesItExistByName(String name, String orgId) {
        return serviceBasicDataAgentMapper.checkDoesItExistByName(name, orgId);
    }

    public List<ServiceBasicDataAgentDO> queryByOrgIdAndPCode(String orgId,String warehouseTypeCOde){
        ServiceBasicDataAgentVO queryAgentParam = new ServiceBasicDataAgentVO();
        queryAgentParam.setOrgId(orgId);
        queryAgentParam.setpCode(warehouseTypeCOde);
        List<ServiceBasicDataAgentDO> serviceBasicDataAgentDOS = serviceBasicDataAgentMapper.queryList(queryAgentParam);
        return serviceBasicDataAgentDOS;
    }
}
